package cn.kgc.javaweb.servlet;

import cn.hutool.crypto.SecureUtil;
import cn.kgc.javaweb.entity.User;
import cn.kgc.javaweb.form.UserLoginForm;
import cn.kgc.javaweb.service.UserService;
import cn.kgc.javaweb.service.impl.UserServiceImpl;
import cn.kgc.javaweb.utils.JSONResult;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

/**
 * @Author: 课工场
 * @Version: v1.0  2023/5/15
 * @Description: 用户模块 跟用户相关的请求全部编写在当前类中   登录 注册  用户管理  crud
 * <p>
 * localhost:8080/user?method=add
 * localhost:8080/user?method=delete
 * localhost:8080/user?method=login
 * localhost:8080/user?method=register
 */
@WebServlet("/user")
public class UserServlet extends BaseServlet {

    private UserService userService = new UserServiceImpl();

    // 登录
    protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1.接收参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String captcha = req.getParameter("captcha");
        String remember = req.getParameter("remember");

        UserLoginForm userLoginForm = new UserLoginForm();

        userLoginForm.setUsername(username);
        userLoginForm.setPassword(password);
        userLoginForm.setCaptcha(captcha);
        userLoginForm.setRemember(remember);

        // 2. 参数的处理  业务处理
        HashMap<String, Object> map = userService.login(userLoginForm, req, resp);
        // 3.根据处理结果响应数据
        JSONResult.writeJson(map, resp);

    }

    // 注册
    protected void register(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1.获取请求参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        // 2.  调用用户的业务层
        HashMap<String, Object> map = userService.register(username, password);
        /**
         *  3. 作出响应   json
         *  code:状态码    0 成功    500 失败
         *  msg: 提示信息
         *  data: 响应的数据
         */
        // 4.将 map以json格式进行响应
        JSONResult.writeJson(map, resp);
    }

    //根据用户名 获取用户相关信息
    protected void getUserByUserName(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {


        // 1.获取请求参数
        String username = req.getParameter("username");
        // 2.  调用用户的业务层
        User user = userService.getUserByUserName(username);
        // 4.将 map以json格式进行响应
        JSONResult.writeJson(user, resp);
    }

    //更新用户信息
    protected void updateUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {


        // 1.获取请求参数
        String username = req.getParameter("username");
        String sex = req.getParameter("sex");
        String birth = req.getParameter("birth");
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        User user = new User();
        user.setUsername(username);
        user.setSex(sex);
        try {
            Date parse = simpleDateFormat.parse(birth);
            user.setBirth(parse);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        // 2.  调用用户的业务层
        HashMap<String, Object> map = userService.updateUser(user);
        // 4.将 map以json格式进行响应
        JSONResult.writeJson(map, resp);
    }

    // 修改密码
    protected void updatePassword(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1.获取请求参数    newPassword
        String oldPassword = req.getParameter("oldPassword");
        String newPassword = req.getParameter("newPassword");
        String username = req.getParameter("username");

        HashMap<String, Object> map = userService.updatePwd(username, newPassword, oldPassword);

        JSONResult.writeJson(map, resp);

    }

    // 退出登录
    protected void logout(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        HttpSession session = req.getSession();
        // 销毁会话
        session.invalidate();
        // 跳转登录页
        resp.sendRedirect(req.getContextPath() + "/login.jsp");

    }


    // 用户信息列表
    protected void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // 获取分页数据
        Integer page = Integer.valueOf(req.getParameter("page"));
        Integer limit = Integer.valueOf(req.getParameter("limit"));

        HashMap<String, Object> users = userService.getList(page, limit);
        JSONResult.writeJson(users, resp);
    }


    // 添加用户信息  管理员操作
    protected void addUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // 1.获取用户信息
        String username = req.getParameter("username");
        String sex = req.getParameter("sex");
        String birth = req.getParameter("birth");

        User user = new User();
        user.setUsername(username);
        // 设置用户的默认密码
        user.setPassword(SecureUtil.md5("888888"));
        user.setSex(sex);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        try {
            user.setBirth(simpleDateFormat.parse(birth));
        } catch (ParseException e) {
            e.printStackTrace();
        }

        String roleId = req.getParameter("roleId");
        user.setRoleId(Long.valueOf(roleId));

        // 调用业务层  添加用户信息
        HashMap<String, Object> map = userService.addUser(user);
        JSONResult.writeJson(map, resp);
    }


    // 管理员修改用户信息  updateUserByRoot
    protected void updateUserByRoot(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // 1.获取用户信息
        String username = req.getParameter("username");
        String sex = req.getParameter("sex");
        String birth = req.getParameter("birth");
        User user = new User();
        user.setUsername(username);
        user.setSex(sex);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        try {
            user.setBirth(simpleDateFormat.parse(birth));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        String roleId = req.getParameter("roleId");
        user.setRoleId(Long.valueOf(roleId));

        // 调用业务层  添加用户信息
        HashMap<String, Object> map = userService.updateUserByRoot(user);
        JSONResult.writeJson(map, resp);

    }


    // 批量删除用户
    protected void deleteBatch(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String[] ids = req.getParameterValues("ids");

        for (String id : ids) {
            System.out.println("id = " + id);
        }

        HashMap<String, Object> map = userService.deleteBatch(ids);
        JSONResult.writeJson(map, resp);

    }

}
